package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"syscall"
)

func main() {
	read := "E:\\goprojects\\src\\helloworld01\\src\\helloword01\\24file\\00_testfile\\test01.txt"
	readAndWriteFile()
	readAndWriteFileWithUtil()
	exists, _ := fileExists(read)
	fmt.Println(exists)
}

// readAndWriteFile
//
//	@Description: 行读取和写入文件
func readAndWriteFile() {
	read := "E:\\goprojects\\src\\helloworld01\\src\\helloword01\\24file\\00_testfile\\test01.txt"
	write := "E:\\goprojects\\src\\helloworld01\\src\\helloword01\\24file\\00_testfile\\test01_copy.txt"
	//打开read路径
	readFile, err := os.Open(read)
	if err != nil {
		fmt.Println("读取文件错误 err=", err)
		return
	}
	defer fileClose(readFile)

	writeFile, err := os.OpenFile(write, syscall.O_WRONLY|syscall.O_CREAT, 0666)
	if err != nil {
		fmt.Println("writeFile err=", err)
		return
	}
	defer fileClose(writeFile)

	reader := bufio.NewReader(readFile)
	writer := bufio.NewWriter(writeFile)
	for {
		//读取文件
		readString, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		//写入文件
		writer.WriteString(readString)
	}
	//Flush
	writer.Flush()

}

// readAndWriteFileWithUtil
//
//	@Description: 使用ioutil工具进行读取和写入文件
func readAndWriteFileWithUtil() {
	read := "E:\\goprojects\\src\\helloworld01\\src\\helloword01\\24file\\00_testfile\\test01.txt"
	write := "E:\\goprojects\\src\\helloworld01\\src\\helloword01\\24file\\00_testfile\\test01_copy.txt"

	var err error
	var data []byte
	//读取文件
	data, err = ioutil.ReadFile(read)
	if err != nil {
		fmt.Println("read file err=", err)
	}
	err = ioutil.WriteFile(write, data, 0666)
	if err != nil {
		fmt.Println("write file err=", err)
	}
}

// fileExists
//
//	@Description:
//	@param path 文件/文件夹  是否存在
//	@return bool 文件是否存在
//	@return error err
func fileExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, err
	}
	return false, err
}

func fileClose(file *os.File) {
	if file != nil {
		err := file.Close()
		if err != nil {
			fmt.Println("file close  err=", err)
		}
	}
}
